package com.chookss.home.audit.resign;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.audit.ApprovalProcessActivity;
import com.chookss.home.entity.ProcessEntity;
import com.chookss.home.entity.ReimbursementDetailEntity;
import com.chookss.home.entity.WorkNewEntity;
import com.chookss.mine.entity.MineInfoEntity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.CircleImageView;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//入职详情页
public class EntryDetailActivity extends BaseAct {

    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.common_right_txt)
    TextView commonRightTxt;
    @BindView(R.id.tvName)
    TextView tvName;
    @BindView(R.id.tvSex)
    TextView tvSex;
    @BindView(R.id.tvBirthday)
    TextView tvBirthday;
    @BindView(R.id.tvPhone)
    TextView tvPhone;
    @BindView(R.id.tvAddress)
    TextView tvAddress;
    @BindView(R.id.tvRole)
    TextView tvRole;
    @BindView(R.id.tvDepartment)
    TextView tvDepartment;
    @BindView(R.id.tvJob)
    TextView tvJob;
    @BindView(R.id.tvLevel)
    TextView tvLevel;
    @BindView(R.id.tvJoinTime)
    TextView tvJoinTime;
    @BindView(R.id.ivHead)
    CircleImageView ivHead;
    @BindView(R.id.tvProcessTitle)
    TextView tvProcessTitle;
    @BindView(R.id.tvProcessTitleInit)
    TextView tvProcessTitleInit;
    @BindView(R.id.llProcessTop)
    LinearLayout llProcessTop;
    @BindView(R.id.tvProcessStatus)
    TextView tvProcessStatus;
    @BindView(R.id.llProcess)
    LinearLayout llProcess;
    @BindView(R.id.emptyProcess)
    View emptyProcess;
    @BindView(R.id.tvCancel)
    TextView tvCancel;
    @BindView(R.id.tvSure)
    TextView tvSure;
    @BindView(R.id.llBottom)
    LinearLayout llBottom;
    @BindView(R.id.llDepartment)
    LinearLayout llDepartment;
    @BindView(R.id.llDepartmentEmpty)
    View llDepartmentEmpty;
    private WorkNewEntity workNewEntity = null;
    private String workflowId = "", projectCode = "";
    private int type = 18;//入职

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_entry_detail);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        workNewEntity = (WorkNewEntity) getIntent().getSerializableExtra("data");
        commonRightTxt.setText("审批流程");
        commonRightTxt.setVisibility(View.VISIBLE);
        if (workNewEntity != null) {
            commonTitleTxt.setText("入职详情");
            selectKaoqinDeail();
            getMyInfo();
        }

    }

    private void getMyInfo() {
        Map<String, String> map = new HashMap<>();
        map.put("employeeCode", workNewEntity.getProjectCode());
        map.put("type", "1");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<MineInfoEntity>>() {
        }.getType(), null, Urls.selectEmployeeDetail, SignUtils2.makeSignStr(map), false, new ObserverCallback<MineInfoEntity>() {
            @Override
            public void onSuccess(MineInfoEntity data) {
                tvName.setText(data.getEmployeeName());
                tvSex.setText(data.getSex());
                tvPhone.setText(data.getPhone());
                if(!Utils.isNull(data.getBirthDate())){
                    tvBirthday.setText(data.getBirthDate());
                }else{
                    tvBirthday.setText("无");
                }
                if(!Utils.isNull(data.getAddress())){
                    tvAddress.setText(data.getAddress());
                }else{
                    tvAddress.setText("无");
                }
                if(!Utils.isNull(data.getRoleNames())){
                    tvRole.setText(data.getRoleNames());
                }else{
                    tvRole.setText("无");
                }
                if(!Utils.isNull(data.getBelgNameOrg())){
                    tvDepartment.setText(data.getBelgNameOrg());
                    llDepartment.setVisibility(View.VISIBLE);
                    llDepartmentEmpty.setVisibility(View.VISIBLE);
                }
                if(!Utils.isNull(data.getPostName())){
                    tvJob.setText(data.getPostName());
                }else{
                    tvJob.setText("无");
                }
                if(!Utils.isNull(data.getLevelName())){
                    tvLevel.setText(data.getLevelName());
                }else{
                    tvLevel.setText("无");
                }
                if(!Utils.isNull(data.getEntryTime())){
                    tvJoinTime.setText(Utils.getTimeSize(data.getEntryTime(), 0, 10));
                }else{
                    tvJoinTime.setText("无");
                }
            }

            @Override
            public void onError(String errorMsg) {
            }
        });

    }

    private void selectKaoqinDeail() {
        //审批基本数据
        Map<String, String> map = new HashMap<>();
        map.put("projectCode", workNewEntity.getProjectCode());
        map.put("type", type + "");
        showLoading();
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<ReimbursementDetailEntity>>() {
        }.getType(), null, Urls.selectKaoqinDeail, SignUtils2.makeSignStr(map), false, new ObserverCallback<ReimbursementDetailEntity>() {
            @Override
            public void onSuccess(ReimbursementDetailEntity data) {
                dismissLoading();
                if (data != null) {
                    workflowId = data.getWorkflowId();
                    projectCode = data.getProjectCode();
                    if (!Utils.isNull(data.getLevelName())) {
                        tvLevel.setText(data.getLevelName());
                    }

                    if (Utils.isNull(data.getAuditFlag())) {
                        llBottom.setVisibility(View.GONE);
                        getProcessData();
                    } else {
                        if ("1".equals(data.getAuditFlag()) || "2".equals(data.getAuditFlag())) {
                            llBottom.setVisibility(View.VISIBLE);
                            if ("2".endsWith(data.getAuditFlag())) {
                                llBottom.setVisibility(View.GONE);
//                                tvSure.setText("修改");
//                                tvCancel.setText("废弃");
                            }
                        } else {
                            llBottom.setVisibility(View.GONE);
                            getProcessData();
                        }
                    }

                }
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getProcessData() {
        //审批进度
        Map<String, String> map = new HashMap<>();
        map.put("projectCode", projectCode);
        map.put("type", type + "");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<ProcessEntity>>>() {
        }.getType(), null, Urls.selectAuditDetailList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<ProcessEntity>>() {
            @Override
            public void onSuccess(List<ProcessEntity> data) {
                String name = "", headUrl = "";
                List<ProcessEntity> processEntityList = new ArrayList<>();
                for (int i = 0; i < data.size(); i++) {
                    processEntityList.add(data.get(i));
                    if (data.get(i).getConnectType().equals("0")) {
                        name = data.get(i).getCreateEmployeeName();
                        headUrl = data.get(i).getHeadPhotoThumbUrl();
                    }
                    if (data.get(i).getEndStep().equals("1")) {
                        ProcessEntity endProcessEntity = new ProcessEntity();
                        if (Utils.isNull(name)) {
                            endProcessEntity.setCreateEmployeeName(data.get(0).getCreateEmployeeName());
                            endProcessEntity.setRealAuditEmployeeName(data.get(0).getCreateEmployeeName());
                        } else {
                            endProcessEntity.setCreateEmployeeName(name);
                            endProcessEntity.setRealAuditEmployeeName(name);
                        }
                        if (Utils.isNull(headUrl)) {
                            endProcessEntity.setHeadPhotoThumbUrl(data.get(0).getHeadPhotoThumbUrl());
                        } else {
                            endProcessEntity.setHeadPhotoThumbUrl(headUrl);
                        }
                        endProcessEntity.setConnectType("0");
                        endProcessEntity.setEndProcess(true);
                        endProcessEntity.setAuditStatus("1");
                        processEntityList.add(endProcessEntity);
                    }
                }
                if (data.size() > 0) {
                    llProcess.setVisibility(View.VISIBLE);
                    emptyProcess.setVisibility(View.VISIBLE);
                    setProcessDetail(processEntityList.get(processEntityList.size() - 1));
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void setProcessDetail(ProcessEntity entity) {
        if (!Utils.isNull(entity.getHeadPhotoThumbUrl())) {
            GlideUtils.loadAvatar(this, entity.getHeadPhotoThumbUrl(), ivHead);
        } else {
            GlideUtils.loadAvatar(this, new ShareUtils().getString(this, StaticClass.ORIGINALURL, ""), ivHead);
        }
        if (entity.isEndProcess()) {
            //已结束
            llProcessTop.setVisibility(View.GONE);
            tvProcessStatus.setText("已结束");
            tvProcessStatus.setTextColor(Color.parseColor("#00C993"));
        } else {
            //getWorkFlowName  环节名称
            //getAuditEmployeeName  项目组
            //getRealAuditEmployeeName   真实审批人
            // connectType //0发起人1行政审批  只有0和1不展示（）中的项目名称，其余的需要展示
            //格式 环节名称（项目名称）
            if ("0".equals(entity.getConnectType()) || "1".equals(entity.getConnectType())) {
                tvProcessTitle.setText(entity.getWorkFlowName());
            } else {
                if (Utils.isNull(entity.getWorkFlowName())) {
                    tvProcessTitle.setText(entity.getWorkFlowName());
                    tvProcessTitleInit.setText(entity.getAuditEmployeeName());
                } else {
                    if (Utils.isNull(entity.getAuditEmployeeName())) {
                        tvProcessTitle.setText(entity.getWorkFlowName());
                        tvProcessTitleInit.setText("");
                    } else {
                        tvProcessTitle.setText(entity.getWorkFlowName());
                        tvProcessTitleInit.setText("(" + entity.getAuditEmployeeName() + ")");
                    }
                }
            }
            //1审核通过 2审核未通过0未审核3废弃
            if ("0".equals(entity.getAuditStatus())) {
                if ("0".equals(entity.getConnectType())) {
                    tvProcessStatus.setText("待修改");
                } else {
                    if (Utils.isNull(entity.getAuditEmployeeName())) {
                        tvProcessStatus.setText("待审批");
                    } else {
                        tvProcessTitleInit.setText("");
                        tvProcessStatus.setText("待" + entity.getAuditEmployeeName() + "审批");
                    }

                }
                tvProcessStatus.setTextColor(Color.parseColor("#FCA817"));
            } else if ("1".equals(entity.getAuditStatus())) {
                if ("0".equals(entity.getConnectType())) {
                    tvProcessStatus.setText("重新提交");
                } else {
                    if ("1".equals(entity.getReplaceCd())) {
                        //超管待审
                        tvProcessStatus.setText("超管代审批通过");
                    } else {
                        tvProcessStatus.setText("审批通过");
                    }

                }
                tvProcessStatus.setTextColor(Color.parseColor("#00C993"));
            } else {
                if ("3".equals(entity.getAuditStatus())) {
                    tvProcessStatus.setText("废弃");
                } else {
                    if ("1".equals(entity.getReplaceCd())) {
                        //超管待审
                        tvProcessStatus.setText("超管代审批不通过");
                    } else {
                        tvProcessStatus.setText("审批不通过");
                    }
                }
                tvProcessStatus.setTextColor(getResources().getColor(R.color.main_color));
            }
        }
    }

    private void passData(int auditStatus) {
        Map<String, Object> map = new HashMap<>();
        //1审核通过 2审核未通过0未审核
        Map<String, String> news = new HashMap<>();
        List<Map<String, String>> lists = new ArrayList<>();
        news.put("id", workflowId);
        news.put("projectCode", projectCode);
//        ////0新闻2图文3补卡4请假7报销9借款10补贴11用章
        news.put("type", type + "");
        news.put("auditStatus", auditStatus + "");
        news.put("employeeCode", workNewEntity.getCreateEmployeeCode());
        lists.add(news);
        map.put("tbKmerWorkFlowProjects", XJson.listToJsArrays(lists));
        showLoading();
        MyHttpRequest.postRequestJson(Urls.auditWorkfolwProject, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("提交成功");
                        EventBus.getDefault().post(new MyEvent("RefreshClockInManagerExamine"));
                        finish();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("提交失败，请稍后重试");
                }
            }
        });
    }

    private void deleteData() {
        Map<String, String> map = new HashMap<>();
        map.put("workflowId", workflowId);
        map.put("qingjiaWorkflowCode", projectCode);
        map.put("workflowType", type + "");//7报销9借款10补贴11用章
        showLoading();
        MyHttpRequest.postRequest(Urls.deleteQingjiaInfo, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("提交成功");
                        EventBus.getDefault().post(new MyEvent("RefreshClockInManagerExamine"));
                        finish();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("提交失败，请稍后重试");
                }
            }
        });
    }

    @OnClick({R.id.common_title_back, R.id.llProcess, R.id.common_right_txt, R.id.tvCancel, R.id.tvSure})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.common_right_txt:
            case R.id.llProcess:
                if (Urls.antiShake.check()) {
                    return;
                }
                intent = new Intent(this, ApprovalProcessActivity.class);
                intent.putExtra("projectCode", workNewEntity.getProjectCode());
                intent.putExtra("type", type);
                startActivity(intent);
                break;
            case R.id.tvCancel:
                if (Urls.antiShake.check()) {
                    return;
                }
//                if (tvCancel.getText().toString().equals("不通过")) {
//                    passData(2);
//                } else {
                    deleteData();
//                }
                break;
            case R.id.tvSure:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (tvSure.getText().toString().equals("通过")) {
                    passData(1);
                } else {
                    //离职修改
                    intent = new Intent(this, ResignHomeActivity.class);
                    intent.putExtra("projectCode", projectCode);
                    intent.putExtra("workflowId", workflowId);
                    startActivity(intent);
                    finish();
                }
                break;

        }
    }

}
